﻿using System;

namespace QQ2564874169.Core.ORM
{
    public interface ITransactionScope : IDisposable
    {
        event EventHandler<TransactionScopeFinishEventArgs> Finish;

        void Commit();
        void Rollback();
    }

    public class TransactionScopeFinishEventArgs : EventArgs
    {
        public bool IsCommited { get; private set; }

        internal TransactionScopeFinishEventArgs(bool isCommited)
        {
            IsCommited = isCommited;
        }
    }

    internal class TransactionScope : ITransactionScope
    {
        public event EventHandler<TransactionScopeFinishEventArgs> Finish;
        private bool _disposed;

        public void Dispose()
        {
            if (_disposed == false)
            {
                _disposed = true;
                OnFinish(false);
            }
        }

        public void Commit()
        {
            if(_disposed)
                throw new ObjectDisposedException(nameof(TransactionScope));
            _disposed = true;
            OnFinish(true);
        }

        public void Rollback()
        {
            if (_disposed)
                throw new ObjectDisposedException(nameof(TransactionScope));
            _disposed = true;
            OnFinish(false);
        }

        private void OnFinish(bool isCommited)
        {
            Finish?.Invoke(this, new TransactionScopeFinishEventArgs(isCommited));
        }
    }
}
